package meijuli.com.join51.business.location;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import com.jhx.common.framework.QuickBaseFragment;
import com.jhx.common.model.EventBean;
import meijuli.com.join51.business.model.LocationDetails;
import com.jhx.common.widget.CommonDialog;
import meijuli.com.join51.business.ui.SearchView;
import meijuli.com.join51.business.utils.LogUtils;
import meijuli.com.join51.business.utils.PermissionUtils;
import meijuli.com.join51.business.utils.StringUtil;
import com.jhx.common.utils.ToastUtil;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * 定位页面
 *
 * @author jack 2017-05-22 09:52
 */
public class LocationFragment extends QuickBaseFragment implements Contract.LocationView,
        SearchView.OnSearchViewActionListener,
        EasyPermissions.PermissionCallbacks {
    MapView mMapView;
    RecyclerView mRecyclerView;
    SearchView mSearchView;
    TextView mAddressText;
    ImageView mImageView;
    private AMap aMap;
    private LocationDetails mLocationDetail;
    private CustomAdapter<PoiItem> mAdapter;
    private LocationPresenterImpl mPresenter;
    private CommonDialog mDialog = null;
    private List<PoiItem> mPoiItemList;
    private boolean setPermissions = false;
    private boolean isRefresh = true;
    /**
     * 搜索关键字
     */
    private String mKeyWord = "街道";
    private double mLatitude;
    private double mLongitude;
    private int mPageIndex = 1;

    @Override
    public View bindView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fagment_loaction, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView = view.findViewById(R.id.mapView);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        mSearchView = view.findViewById(R.id.mySearchView);
        mAddressText = view.findViewById(R.id.currentSelectView);
        mImageView = view.findViewById(R.id.choosedImageView);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPoiItemList = new ArrayList<>();
        mLocationDetail = new LocationDetails();
        mPresenter = new LocationPresenterImpl();
        mPresenter.setView(this);
        mPresenter.setContext(getActivity());
        mMapView.onCreate(savedInstanceState);
        mSearchView.setOnSearchViewActionListener(this);
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
            //初始化地图控制器对象
            if (aMap == null) {
                aMap = mMapView.getMap();
                mPresenter.initLocation(aMap);
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CommonDialog dialog = new CommonDialog(getActivity());
                dialog.setMessage("为了保证聚惠侠商家版可以正常使用,请在设置-应用-聚惠侠商家版-权限，开启定位权限");
                dialog.setConfirmBtn("设置");
                dialog.show();
                dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onConfirmClick(View view) {
                        setPermissions = true;
                        PermissionUtils.getInstance().toSetting(getActivity());
                    }

                    @Override
                    public void onCancelClick(View view) {
                        ToastUtil.getInstance().showToast("定位权限被拒绝");
                    }
                });
            }else {
                EasyPermissions.requestPermissions(this, "应用需要地图定位权限，请授权",
                        1001,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION);
            }
        }
        mAdapter = initAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        setTitle("地图定位");
        setMenuText("确定");
        if (mMenuText != null) {
            mMenuText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    compelteLocation();
                    getActivity().finish();
                }
            });
        }
    }

    private CustomAdapter<PoiItem> initAdapter() {
        final List<PoiItem> selectItem = new ArrayList<>();
        CustomAdapter<PoiItem> adapter = new CustomAdapter<PoiItem>(mPoiItemList,
                getActivity(),
                R.layout.map_search_nearby_view_item,
                null) {
            @Override
            public void onBindData(CustomHolder holder, final int position, final PoiItem poiItem) {
                TextView locationView = holder.findView(R.id.locationView);
                final View choosedImageView = holder.findView(R.id.choosedImageView);
                TextView detailAddressView = holder.findView(R.id.detailAddressView);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LatLonPoint location = poiItem.getLatLonPoint();
                        // 拼接选中列表的某一项展示给用户看
                        String provinceName = poiItem.getProvinceName();
                        String cityName = poiItem.getCityName();
                        String snippet = poiItem.getSnippet();
                        mLatitude = location.getLatitude();
                        mLongitude = location.getLongitude();
                        mLocationDetail.setProvince(provinceName);
                        mLocationDetail.setAddrStr(provinceName + cityName + snippet);
                        mLocationDetail.setCity(cityName);
                        mLocationDetail.setDistrict(poiItem.getAdName());
                        mLocationDetail.setStreet(snippet);
                        mLocationDetail.setLatitude(mLatitude);
                        mLocationDetail.setLongitude(mLongitude);
                        mImageView.setVisibility(View.INVISIBLE);
                        selectItem.clear();
                        selectItem.add(poiItem);
                        mAdapter.notifyDataSetChanged();
                    }
                });
                String snippet = poiItem.getSnippet();
                String provinceName = poiItem.getProvinceName();
                provinceName = StringUtil.isEmpty(provinceName) ? "" : provinceName;
                String cityName = poiItem.getCityName();
                cityName = StringUtil.isEmpty(cityName) ? "" : cityName;
                detailAddressView.setText(snippet);
                if (selectItem.contains(poiItem)) {
                    choosedImageView.setVisibility(View.VISIBLE);
                } else {
                    choosedImageView.setVisibility(View.GONE);
                }
                locationView.setText(provinceName + cityName + poiItem.getAdName());
            }
        };
        return adapter;
    }

    @Override
    public void onAction(int action, String result) {
        switch (action) {
            case ACTION_DONE:
                hideSoftKeyboard();
                if (StringUtil.isEmpty(result)) {
                    return;
                }
                mPageIndex = 0;
                mKeyWord = result;
                mPresenter.searchNearby(mLatitude, mLongitude, mKeyWord, mPageIndex);
                break;
            default:

                break;
        }
    }

    /**
     * 关闭软键盘
     */
    public void hideSoftKeyboard() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void setData(List<PoiItem> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        if (isRefresh) {
            mPoiItemList.clear();
        }
        mPoiItemList.addAll(data);
        mAdapter.updateView(mPoiItemList);
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void locationResult(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            mLatitude = aMapLocation.getLatitude();
            mLongitude = aMapLocation.getLongitude();
            mImageView.setVisibility(View.VISIBLE);
            mLocationDetail.setProvince(aMapLocation.getProvince());
            mLocationDetail.setCity(aMapLocation.getCity());
            mLocationDetail.setDistrict(aMapLocation.getDistrict());
            mLocationDetail.setAddrStr(aMapLocation.getAddress());
            mLocationDetail.setStreet(getStreet(aMapLocation.getAddress()));
            mLocationDetail.setLatitude(mLatitude);
            mLocationDetail.setLongitude(mLongitude);
            mPresenter.searchNearby(mLatitude, mLongitude, mKeyWord, mPageIndex);
            mAddressText.setText(aMapLocation.getAddress());
            String errText = "位置信息：" + aMapLocation.getAddress();
            LogUtils.e("AmapAddress------->", errText);
        } else {
            String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
            CrashReport.postCatchedException(new Throwable(errText));
            ToastUtil.getInstance().showToast("定位失败，请稍后重试");
        }
    }

    private String getStreet(String address) {
        int index = -1;
        if(address.contains("区")) {
            index = address.indexOf("区");
        } else if(address.contains("县")) {
            index = address.indexOf("县");
        }
        return address.substring(index + 1, address.length());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMapView == null) {
            return;
        }
        mMapView.onResume();
        if(setPermissions) {
            checkPermissions();
        }
    }

    private void checkPermissions() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
            setPermissions = false;
            //初始化地图控制器对象
            if (aMap == null) {
                aMap = mMapView.getMap();
                mPresenter.initLocation(aMap);
            }
        } else {
            ToastUtil.getInstance().showToast("定位权限已拒绝");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMapView == null) {
            return;
        }
        mMapView.onPause();
        mPresenter.deactivate();
    }

    public void compelteLocation() {
        if(mLocationDetail != null && !TextUtils.isEmpty(mLocationDetail.getAddrStr())) {
            EventBean<LocationDetails> eventBean = new EventBean<>(EventBean.STATUS_UPDATE_LOCATION);
            eventBean.setEvent(mLocationDetail);
            EventBus.getDefault().post(eventBean);
        }
    }

    @Override
    public void onDestroyView() {
        mMapView.onDestroy();
        super.onDestroyView();
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView == null) {
            return;
        }
        mMapView.onSaveInstanceState(outState);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 以下方法将把权限结果执行给EasyPermission
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
            mPresenter.initLocation(aMap);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        checkPermission();
    }

    private void checkPermission() {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, permissionList)) {
            if (mDialog == null) {
                mDialog = new CommonDialog(getActivity());
            }
            mDialog.setMessage("该功能需要使用您的定位，请前往设置-权限管理，开启定位权限");
            mDialog.setCanceledOnTouchOutside(false);
            if (!mDialog.isShowing()) {
                mDialog.show();
            }
            mDialog.setOnClickListener(new CommonDialog.OnClickListener() {
                @Override
                public void onConfirmClick(View view) {
                    PermissionUtils.getInstance().toSetting(getActivity());
                    getActivity().finish();
                }

                @Override
                public void onCancelClick(View view) {
                    getActivity().finish();
                }
            });
            mDialog.setCancelable(false);
        } else {
            getActivity().finish();
        }
    }

    @Override
    protected boolean showToolbar() {
        return true;
    }
}
